package com.bby.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.bby.common.exception.BBYException;
import com.bby.common.model.*;
import com.bby.common.utils.BBYUtils;
import com.bby.common.utils.StatusCode;
import com.bby.user.bean.UserGroupVO;
import com.bby.user.bean.UserPubsVO;
import com.bby.user.bean.req.FavoriteActionReq;
import com.bby.user.bean.req.UserGroupActionReq;
import com.bby.user.manager.UserActionManager;
import com.bby.user.manager.UserinfoManager;
import com.bby.user.pojo.ServiceResult;
import com.bby.user.service.UserActionService;
import com.bby.user.manager.TokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserActionServiceImpl implements UserActionService {
    private final UserinfoManager userinfoManager;
    private final UserActionManager userActionManager;
    private final TokenManager tokenManager;

    Logger logger = LoggerFactory.getLogger(this.getClass());
    public UserActionServiceImpl(UserinfoManager userinfoManager, UserActionManager userActionManager, TokenManager tokenManager) {
        this.userinfoManager = userinfoManager;
        this.userActionManager = userActionManager;
        this.tokenManager = tokenManager;
    }

    public ServiceResult getUserInfoByEmail(String email) {
        ServiceResult result = new ServiceResult();
        try {
            UserCustomInfo userInfo = userinfoManager.findUserCustomInfoByEmail(email);
            result.setCode(ServiceResult.CODE_OK);
            result.setData(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            result.setCode(ServiceResult.CODE_NOT_FIND);
            result.setMsg("数据库连接错误！");
        }
        return result;
    }


    @Override
    public UserSettings setUserSettings(String userId, UserSettings settings) throws BBYException {
        BBYUtils.checkEmpty(settings.getDefaultPmType());
        settings.setUserId(userId);
        return userActionManager.saveUserSettings(settings);
    }

    @Override
    public UserSettings getUserSettings(String userId) {
        return userActionManager.getUserSettings(userId);
    }

    @Override
    public List<FavoriteGroup> favoriteOp(String userId, FavoriteActionReq params) throws BBYException {
        switch (params.getOpera()){
            case "addFav":
                BBYUtils.checkEmpty(params.getNewName(),params.getGroupId(),params.getFileId());
                Favorite favorite = new Favorite(params.getFileId(),params.getNewName());
                userActionManager.addFavorite(userId,params.getGroupId(),favorite);
                break;
            case "addGroup":
                BBYUtils.checkEmpty(params.getNewName());
                FavoriteGroup group = new FavoriteGroup(params.getNewName());
                userActionManager.addFavoriteGroup(userId,group);
                break;
            case "renameFav":
                BBYUtils.checkEmpty(params.getNewName(),params.getGroupId(),params.getFileId());
                userActionManager.renameFavorite(userId,params.getGroupId(),params.getFileId(), params.getNewName());
                break;
            case "renameGroup":
                BBYUtils.checkEmpty(params.getNewName(),params.getGroupId());
                userActionManager.renameFavoriteGroup(userId,params.getGroupId(),params.getNewName());
                break;
            case "deleteFav":
                BBYUtils.checkEmpty(params.getFileId(),params.getGroupId());
                userActionManager.deleteFavorite(userId,params.getGroupId(),params.getFileId());
                break;
            case "deleteGroup":
                BBYUtils.checkEmpty(params.getGroupId());
                userActionManager.deleteFavoriteGroup(userId,params.getGroupId());
                break;
            default: throw new BBYException(StatusCode.INPUT_ERROR,"参数 opera 错误: "+ params.getOpera());
        }
        return getFavorites(userId);
    }

    @Override
    public List<FavoriteGroup> getFavorites(String userId) throws BBYException {
        List<FavoriteGroup> list = userActionManager.getFavorites(userId);
        return list==null? new ArrayList<>():list;
    }

    @Override
    public List<UserGroupVO> userGroups(String userId, UserGroupActionReq params) throws BBYException {
        switch (params.getOpera()){
            case "addUser":
                BBYUtils.checkEmpty(params.getUserId(),params.getGroupId());
                logger.debug("添加用户组：{}到：{}",params.getUserId(),params.getGroupId());
                userActionManager.addUserToGroup(userId,params.getGroupId(),params.getUserId());
                break;
            case "addGroup":
                BBYUtils.checkEmpty(params.getNewName());
                UserGroup userGroup = new UserGroup(params.getNewName());
                logger.debug("添加用户组：{}",userGroup);
                userActionManager.addUserGroup(userId,userGroup);
                break;
            case "renameGroup":
                BBYUtils.checkEmpty(params.getNewName(),params.getGroupId());
                userActionManager.renameUserGroup(userId,params.getGroupId(),params.getNewName());
                break;
            case "deleteUser":
                BBYUtils.checkEmpty(params.getUserId(),params.getGroupId());
                userActionManager.deleteUserFromGroup(userId,params.getGroupId(),params.getUserId());
                break;
            case "deleteGroup":
                BBYUtils.checkEmpty(params.getGroupId());
                userActionManager.deleteUserGroup(userId,params.getGroupId());
                break;
            default: throw new BBYException(StatusCode.INPUT_ERROR,"参数 opera 错误: "+ params.getOpera());
        }
        return getUserGroups(userId);
    }
    @Override
    public List<UserGroupVO> getUserGroups(String userId) throws BBYException {
        List<UserGroup> list = userActionManager.getUserGroup(userId);
        List<UserGroupVO> res = new ArrayList<>();
        if (ObjectUtil.isEmpty(list)){
            return res;
        }
        for (UserGroup userGroup : list) {
            UserGroupVO vo = new UserGroupVO(userGroup);
            Set<String> ids = userGroup.getContent();
            if (ids!=null&&ids.size()>0){
                List<UserCustomInfo> customInfos = userinfoManager.findCustomInfos(userGroup.getContent());
                List<UserGroupVO.UserGroupContentVO> content = customInfos
                        .stream()
                        .map(user -> new UserGroupVO.UserGroupContentVO(
                                user.getUserId(),user.getUsername()))
                        .collect(Collectors.toList());
                vo.setContent(content);
            }else {
                vo.setContent(new ArrayList<>());
            }
            res.add(vo);
        }
        return res;
    }

    @Override
    public UserPubsVO searchUser(String regex, Integer page, Integer limit) {
        return userActionManager.searchUser(regex,page,limit);
    }


}
